package com.woniuxy.controller;

import com.alibaba.excel.EasyExcel;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.mapper.AppointmentRecordMapper;
import com.woniuxy.mapper.DepartmentMapper;
import com.woniuxy.mapper.DoctorScheduleMapper;
import com.woniuxy.mapper.HospitalMapper;
import com.woniuxy.pojo.*;
import com.woniuxy.pojo.dto.AppointmentRecordDTO;
import com.woniuxy.pojo.dto.SearchAppointmentRecordDTO;
import com.woniuxy.pojo.vo.AppointmentRecordVO;
import com.woniuxy.service.AppointmentRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("appointmentRecord")
@Api(tags = "预约记录接口")
@Slf4j
public class AppointmentRecordController {
    @Autowired
    private AppointmentRecordService appointmentRecordService;
    @Autowired
    private AppointmentRecordMapper appointmentRecordMapper;
    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private HospitalMapper hospitalMapper;

    @Autowired
    private DepartmentMapper departmentMapper;
    @GetMapping("/getAppointmentRecord/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询所有预约记录")
    public Object getAppointmentRecord(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        MyPageData doctorSchedules = appointmentRecordService.getAppointmentRecord(pageNum, pageSize);
        return Result.ok(doctorSchedules);
    }
    @GetMapping("/getAppointmentDetail/{id}")
    @ApiOperation(value = "查询预约记录详情")
    public Result getAppointmentDetail(@PathVariable("id") Integer id) {
        AppointmentRecordVO appointmentDetail = appointmentRecordService.getAppointmentDetail(id);
        return Result.ok(appointmentDetail);
    }
    @GetMapping("/download")
    @ApiOperation(value = "导出详情的Excel表")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("体检详情列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        MyPageData appointmentRecord = appointmentRecordService.getAppointmentRecord(1, 9);
        List data = appointmentRecord.getData();
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(response.getOutputStream(), DoctorSchedule.class).sheet("体检").doWrite(data);
        outputStream.flush();
        outputStream.close();
    }
    @GetMapping("/getFetchData/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询所有挂号订单")
    public Result getFetchData(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        MyPageData doctorSchedules = appointmentRecordService.getFetchData(pageNum, pageSize);
        return Result.ok(doctorSchedules);
    }
    @GetMapping("/getStatuss")
    @ApiOperation(value = "查询所有预约状态")
    public Result getStatuss() {
        List<String> statuss = appointmentRecordService.getStatuss();
        return Result.ok(statuss);
    }
    @PostMapping("/searchAppointmentRecord/{pageNum}/{pageSize}")
    @ApiOperation(value = "条件查询所有的预约订单")
    public Result searchAppointmentRecord(@PathVariable("pageNum") Integer pageNum,  @PathVariable("pageSize") Integer pageSize,@RequestBody SearchAppointmentRecordDTO queryDTO){
        MyPageData list=appointmentRecordService.searchAppointmentRecord(pageNum, pageSize,  queryDTO);
        return Result.ok(list);
    }
    @GetMapping("/download2")
    @ApiOperation(value = "导出详情的Excel表")
    public void download1(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("挂号订单数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 2. 查询所有记录
        List<AppointmentRecord> records = appointmentRecordMapper.selectList(null);

        // 3. 转换为DTO并修复字段类型
        List<AppointmentRecordDTO> dataList = records.stream().map(record -> {
            AppointmentRecordDTO dto = new AppointmentRecordDTO();
            BeanUtils.copyProperties(record, dto);

            // 获取排班信息
            DoctorSchedule schedule = doctorScheduleMapper.selectById(record.getScheduleId());
            if (schedule != null) {
                // 设置费用
                dto.setFee(schedule.getFee());

                // 关键修复：将 Object 类型的时间段转换为字符串
                dto.setTimePeriod(schedule.getTimePeriod() != null ?
                        schedule.getTimePeriod().toString() : "");

                // 设置就诊日期
                dto.setScheduleDate(schedule.getScheduleDate());

                // 处理医院名称
                if (schedule.getHospitalId() != null) {
                    Hospital hospital = hospitalMapper.selectById(schedule.getHospitalId());
                    if (hospital != null) {
                        dto.setHospitalName(hospital.getName());
                    }
                }

                // 处理科室名称
                if (schedule.getDepartmentId() != null) {
                    Department department = departmentMapper.selectById(schedule.getDepartmentId());
                    if (department != null) {
                        if (department.getParentId() != null) {
                            Department parentDept = departmentMapper.selectById(department.getParentId());
                            if (parentDept != null) {
                                dto.setDepartmentName(parentDept.getName() + ">" + department.getName());
                            } else {
                                dto.setDepartmentName(department.getName());
                            }
                        } else {
                            dto.setDepartmentName(department.getName());
                        }
                    }
                }
            }

            // 设置状态显示文本
            if (dto.getStatus() != null) {
                switch (dto.getStatus().toLowerCase()) {
                    case "unpaid":
                        dto.setStatus("未支付");
                        break;
                    case "paid":
                        dto.setStatus("已支付");
                        break;
                    case "canceled":
                        dto.setStatus("已取消");
                        break;
                    case "completed":
                        dto.setStatus("已完成");
                        break;
                    default: // 保持原样
                }
            }

            return dto;
        }).collect(Collectors.toList());

        // 4. 导出Excel
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, AppointmentRecordDTO.class)
                    .sheet("挂号订单")
                    .doWrite(dataList);
        }
    }
    @PostMapping("/searchAppointment/{pageNum}/{pageSize}")
    @ApiOperation(value = "高级条件查询所有的预约订单")
    public Result searchAppointment(@PathVariable("pageNum") Integer pageNum,  @PathVariable("pageSize") Integer pageSize,@RequestBody SearchAppointmentRecordDTO queryDTO){
        MyPageData list=appointmentRecordService.searchAppointment(pageNum,pageSize,queryDTO);
        return Result.ok(list);
    }
    @GetMapping("/getOrderDetail/{id}")
    @ApiOperation(value = "查询预约订单详情")
    public Result getOrderDetail(@PathVariable("id") Integer id) {
        AppointmentRecordDTO appointmentRecordDTO = appointmentRecordService.getOrderDetail(id);
        return Result.ok(appointmentRecordDTO);
    }
}
